#include "opencv_qt_utils.h"
#include <stdint.h>


QImage OpencvQtUtils::toQimage(const cv::Mat &image, bool swap_rgb)
{
    if (image.dims > 2)
    {
        //lyWarning("cv::Mat维度过高，image.dims：") << image.dims;
        return QImage();
    }

    QImage::Format format;
    switch (image.type())
    {
    case CV_8UC1:
        format = QImage::Format_Indexed8;
        break;
    case CV_8UC3:
        format = QImage::Format_RGB888;
        break;
    default:
        //lyWarning("不支持的图像类型，image.type(): ") << image.type();
        return QImage();
    }

}

cv::Mat OpencvQtUtils::toCvMat(const QImage &image, bool swap_rgb)
{
    int type;
    int bytes_per_pix;
    switch (image.format())
    {
    case QImage::Format_Indexed8:
        type = CV_8UC1;
        bytes_per_pix = 1;
        break;
    case QImage::Format_RGB888:
        type = CV_8UC3;
        bytes_per_pix = 3;
        break;
    default:
        //lyWarning("不支持的图像类型，image.format(): ") << image.format();
        return cv::Mat();
    }

    QImage temp_image = image;
    if (swap_rgb && bytes_per_pix != 1)
    {
        temp_image = image.rgbSwapped();
    }

    size_t data_size = temp_image.height() * temp_image.width() * bytes_per_pix;
    uchar* data = new uchar[data_size];
    if (temp_image.bytesPerLine() == temp_image.width() * bytes_per_pix)
    {
        memcpy(data, temp_image.constBits(), data_size);
    }
    else
    {
        for (int i = 0; i < temp_image.height(); ++i)
        {
            memcpy(data + i * temp_image.width() * bytes_per_pix,
                   temp_image.constBits() + temp_image.bytesPerLine(),
                   temp_image.width() * bytes_per_pix);
        }
    }
    return cv::Mat(temp_image.height(),
                   temp_image.width(),
                   type,
                   data,
                   temp_image.width() * bytes_per_pix);
}
